var express = require("express");
var router = express.Router();
let service = require("../service/goodsService");
let typeinfoService = require("../service/typeinfoService");

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});
router.get("/list", async (req, res, next) => {
  let result = await service.query({});
  res.json({
    code: 200,
    list: result,
  });
});
//后端的单个新增接口
router.post("/add", async (req, res, next) => {
  let { typeid, img, name, size } = req.body;
  //取值
  let result = await service.add([{ typeid, img, name, size }]);
  //把数据放到数据库
  res.json({
    code: 200,
    msg: "新增成功",
    data: result,
  });
});
//后端的多个新增接口
router.post("/insertmany", async (req, res, next) => {
  let { list } = req.body;

  let result1 = await typeinfoService.query({
    type: { $in: list.map((item) => item.type) },
  });//找到需要用的type

  let  arr  = list.map(item=>{
    item.typeid = result1.filter(info=>item.type==info.type)[0]["_id"];
    return item;
  })

  //取值
  let result = await service.add(arr);
  //把数据放到数据库
  res.json({
    code: 200,
    msg: "新增成功",
    data: result
  });
});

router.delete("/del", async (req, res, next) => {
  //删除的接口
  let { id } = req.body; //获取编号
  await service.del({ _id: id });
  res.json({
    code: 200,
    msg: "删除成功",
  });
});

module.exports = router;
